﻿using Dotnet.Code;
using Dotnet.FormExtensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Dotnet.FormExtensions.UsrControl
{
    public partial class UcDataGridViewPage : UserControl
    {
        private DataTable _dataTable = null; //原始DataTable
        private DataTable _dataTableSearch = null;  //搜索时生成的DataTable;
        private string _cellValue = "";
        private int _pagesize = 100;  //每页条数(默认每页显示100条)
        private int _pagecount = 0;  //总页面数
        private int _currentpage = 1;
        private int _max = 0;
        private int _currentRow = 0;//当前行用于table复制的起始行
        private Dictionary<string, string> _dictColumns = new Dictionary<string, string>();
        private EventHandler<ToolStripMenuItemClickEventArgs> _toolStripMenuItemClick = null;

        public UcDataGridViewPage()
        {
            InitializeComponent();
            cmbCondition.Text = "包含";
        }
        #region 属性Start
        public DataTable DataSource
        {
            get{return this._dataTable;}
            set
            {
                if (value == null)
                {
                    dataGridMain.DataSource = null;
                    return;
                }
                this._dataTable = value;
                _pagecount = (int)Math.Ceiling(_dataTable.Rows.Count * 1.0 / _pagesize); //页面数
                lblRowsCount.Text = _dataTable.Rows.Count.ToString();
                SetPageControlState(_pagecount);
            }
        }
        public int PageSize { get => _pagesize; set => _pagesize = value; }
        public DataGridView DataGridView
        {
            get { return this.dataGridMain;}
        }
        public string ColName
        {
            set
            {
                this.txtColName.AutoSetTextWidth(value);// = value;
            }
        }
        private DataTable DataTableSearch
        {
            get { return this._dataTableSearch; }
            set
            {
                this._dataTableSearch = value;

                //SetPageControlState(_dataTableSearch, 20);
            }
        }
        #endregion  属性End

        #region  私有方法Start
        /// <summary>
        /// 设置分页控件状态
        /// </summary>
        /// <param name="rowsCount">数据总行数</param>
        /// <param name="pageSize">每页展示行数</param>
        private void SetPageControlState(int pageCount,int currPage=1)
        {
            this.txtPageSize.Text = _pagesize.ToString();
            this.txtNavPosition.Text = _currentpage.ToString();
            int rowsCount = 0;
            if (_dataTable != null) rowsCount = _dataTable.Rows.Count;
            this.bindingNavigatorCountItem.Text = $"共 {pageCount.ToString()} 页 {rowsCount} 条记录";
            txtCurrentPage.Text = currPage.ToString();
            SetBtnPageEnabled(currPage, _pagecount);
            this.cmbPage.Items.Clear();
            if (_pagecount == 0)
            {
                this.cmbPage.Items.Add("第" + _pagecount + "页");
            }
            for (int i = 1; i <= _pagecount; i++)
            {
                this.cmbPage.Items.Add("第" + i + "页");
            }
            this.cmbPage.Text = "第" + currPage + "页";
        }
        private void BindSource(DataTable dt)
        {
            if (_pagesize >= dt.Rows.Count)
            {
                dataGridMain.DataSource = dt;
                return;
            }
            DataTable pageTable = dt.Clone();
            pageTable.TableName = "tb";
            int start = (_currentpage - 1) * _pagesize;
            int end = _currentpage * _pagesize;
            if (end > dt.Rows.Count) end = dt.Rows.Count;
            for (int i = start; i < end; i++)
            {
                pageTable.ImportRow(dt.Rows[i]);//导入maxRows条数据展示 
            }
            Console.WriteLine($"start:{start} end:{end}  Currentpage:{_currentpage}");
            dataGridMain.DataSource = pageTable;
        }
        private void SetBtnPageEnabled(int currPage, int pageCount)
        {
            if (currPage == 1 && pageCount == 1) //不分页
            {
                this.btnFirst.Enabled = false;
                this.btnForward.Enabled = false;
                this.btnLast.Enabled = false;
                this.btnNext.Enabled = false;
            }
            else if (currPage == 1 && pageCount > 1) //第一页
            {
                this.btnFirst.Enabled = false;
                this.btnForward.Enabled = false;
                this.btnLast.Enabled = true;
                this.btnNext.Enabled = true;
            }
            else if (currPage > 1 && currPage < pageCount) //中间页
            {
                this.btnFirst.Enabled = true;
                this.btnForward.Enabled = true;
                this.btnLast.Enabled = true;
                this.btnNext.Enabled = true;
            }
            else if (currPage > 1 && currPage == pageCount) //最后一页
            {
                this.btnFirst.Enabled = true;
                this.btnForward.Enabled = true;
                this.btnLast.Enabled = false;
                this.btnNext.Enabled = false;
            }
        }

        private void RefreshDgvMain()
        {
            TextChangeState = "刷新";
            txtKw.Clear();
            _dictColumns.Clear();
            sb.Clear();
            txtColName.Clear();
            chkColumns.Checked = false;
            TextChangeState = "";
            //  dgvMain.DataSource = null;
            //this.DataTable = this._dataTable;
        }
        private void RefreshDb()
        {
            //if (this._db == null)
            //    return;
            //TextChangeState = "刷新";
            //txtKw.Clear();
            //TextChangeState = "";
            //dgvMain.DataSource = null;
            //DataTable dt = _db.GetDataTable(_dataTable.TableName);
            //this.DataTable = dt;
        }
        #endregion

        [Category("自定义事件"), Description("命令解析"), Browsable(true)]
        public event EventHandler<ToolStripMenuItemClickEventArgs> ToolStripMenuItemClick
        {
            add { _toolStripMenuItemClick += value; }
            remove { _toolStripMenuItemClick -= value; }
        }
        protected void OnToolStripMenuItemClick(ToolStripMenuItemClickEventArgs e)
        {
            var temp = System.Threading.Volatile.Read(ref _toolStripMenuItemClick);
            if (temp != null)
            {
                temp(this, e);
            }
        }
        #region 事件
        //翻页事件
        private string TextChangeState = "";

        #endregion
        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
          /*  string type = (sender as ToolStripMenuItem).Text.Trim();
            string colName = dgvMain.CurrentCell?.OwningColumn.Name;
            OnToolStripMenuItemClick(new ToolStripMenuItemClickEventArgs() { Name=type});
            switch (type)
            {
                case "删除":
                    DataGridViewRow row = dgvMain.CurrentRow;
                    dgvMain.Rows.Remove(row);
                    break;
                case "除重":            
                    DataTable temp=_dataTable.DefaultView.ToTable(true, colName);
                    txtKw.Text = type;
                    this.DataTableSearch = temp;
                    break;
                case "过滤":
                    var temp1 = (from item in _dataTable.AsEnumerable() where item.Field<object>(colName).ToString() == dgvMain.CurrentCell.Value.ToString() select item);
                    DataTable temp2 = temp1.CopyToDataTable();
                    txtKw.Text = type;
                    this.DataTableSearch = temp2;
                    break;
                case "修改":
                    dgvMain.ReadOnly = false;
                    dgvMain.EditMode = DataGridViewEditMode.EditOnEnter;
                    dgvMain.CurrentCell.ReadOnly = false;
                    dgvMain.BeginEdit(true);
                    DataGridViewRow row1 = dgvMain.CurrentCell.OwningRow;
                    UpdateRow(row1, dgvMain.CurrentCell);
                    dgvMain.ReadOnly = true;
                    break;
                case "求和":
                    string col_valueType = dgvMain.CurrentCell.OwningColumn.ValueType.Name;
                    if (col_valueType == "Decimal")
                    {

                    }
                    break;
                case "刷新": RefreshDgvMain(); break;
                case "刷新数据库":
                    RefreshDb();
                    break;
                default:
                    break;
            }*/
        }

        private void dgvMain_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            //LogFactory.GetLogger("UcDataGridViewSearchPager").Error(e.Exception.StackTrace);
        }

        private void 导出ExcelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExcelHelper exel = new ExcelHelper();
            DataTable dt = null;// dgvMain.DataSource as DataTable;
            if (dt == null)
                return;
            if(dt.Columns.Contains("TABLE_NAME") && dt.Columns.Contains("TABLE_NAME"))
            {
                dt.DefaultView.Sort = "TABLE_NAME ASC,ORDINAL_POSITION ASC";
                dt = dt.DefaultView.ToTable();
            }
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Excel导出(*.xls)|*.xls|所有文件(*.*)|*.*"; ;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string fileName = sfd.FileName;
                exel.ToExcel(dt, fileName);
            }
        }

        private void dataGridMain_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X + 1, e.RowBounds.Location.Y, dataGridMain.RowHeadersWidth - 2, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dataGridMain.RowHeadersDefaultCellStyle.Font, rectangle,
                Color.Red, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void dataGridMain_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            txtKw.Focus();
            string colName = dataGridMain.CurrentCell?.OwningColumn.Name;

            if (chkColumns.Checked == true)
            {
                if (!_dictColumns.ContainsKey(colName))
                {
                    _dictColumns.Add(colName, "");
                    sb.Append(colName).Append(",");
                }
                txtColName.AutoSetTextWidth(sb.ToString().TrimEnd(','));
            }
            else
            {
                txtColName.AutoSetTextWidth(colName);
                this._cellValue = (dataGridMain.CurrentCell.Value == DBNull.Value || dataGridMain.CurrentCell.Value == null) ? "" :
                    dataGridMain.CurrentCell.Value.ToString();
            }
        }
    }
}
